﻿using System;
using System.Threading;
using System.Windows.Forms;
using Core.DependencyInjection;
using DounloderV2WinFormsUI.ResoucesStrings;

namespace DounloderV2WinFormsUI
{
    static class AppRun
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += ThreadException_UnhandledException;
            NinjectFactory.Wire(new ApplicationModule());

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(InitStartForms());
        }

        private static MainForm InitStartForms()
        {
            var result = NinjectFactory.Resolve<MainForm>();
            result.Text = GlobalStrings.AppName;
            return result;
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            UnhandledExceptionLog((Exception)e.ExceptionObject);
        }

        private static void ThreadException_UnhandledException(object sender, ThreadExceptionEventArgs e)
        {
           
            UnhandledExceptionLog(e.Exception);
        }

        private static void UnhandledExceptionLog(Exception e)
        {
            var loger = NinjectFactory.Resolve<AppLoger.Implementation.AppLoger>();
            try { loger.Fatal(e); }
            catch (Exception ex)
            {
                try { loger.Fatal(ex); }
                finally { Application.Exit(); }
            }
            finally { Application.Exit(); }
        }
    }
}
